package com.jsz.yun.ai.field.exception;

import com.jsz.yun.ai.field.common.Rsp;
import com.jsz.yun.ai.field.enums.ResultCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 异常处理
 * @author lami
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public Rsp<Object> handleBusinessException(BusinessException ex, HttpServletRequest request) {
        // 记录异常信息
        logger.error("BusinessException occurred: {}", ex.getMessage(), ex);
        // 创建包含错误码和错误消息的响应
        Rsp<Object> rsp = new Rsp();
        rsp.setCode(ex.getCode());
        rsp.setMessage(ex.getMessage());
        String traceIdFromRequest = getTraceIdFromRequest(request);
        rsp.setTraceId(traceIdFromRequest);
        return rsp;
    }

    @ExceptionHandler(Exception.class)
    public Rsp<Object> handleException(Exception ex, HttpServletRequest request) {
        // 记录异常信息
        logger.error("Exception occurred: {}", ex.getMessage(), ex);
        // 创建包含错误码和错误消息的响应
        Rsp<Object> rsp = new Rsp();
        rsp.setCode(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode());
        rsp.setMessage(ResultCodeEnum.INTERNAL_SERVER_ERROR.getMessage());
        String traceIdFromRequest = getTraceIdFromRequest(request);
        rsp.setTraceId(traceIdFromRequest);
        return rsp;
    }

    private String getTraceIdFromRequest(HttpServletRequest request) {
         String traceId = request.getHeader("traceId");

         if (traceId == null) {
             traceId = String.valueOf(System.currentTimeMillis());
         }
        return traceId;
    }
}